package com.trsvax.gwthello.client.gwtui.widgets;

import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.event.logical.shared.BeforeSelectionEvent;
import com.google.gwt.event.logical.shared.BeforeSelectionHandler;
import com.google.gwt.i18n.client.Dictionary;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.TabPanel;
import com.trsvax.gwthello.client.Tapestry;

public class TabPanelWidget extends Composite {

	private final Dictionary dictionary;
	private final Element element;

	public TabPanelWidget(Element el, Dictionary d) {
		dictionary = d;
		element = el;
		NodeList<Element> nl = element.getElementsByTagName("dt");

		TabPanel tp = new TabPanel();
		for (int i = 0; i < nl.getLength(); i++) {
			Element e = nl.getItem(i).getNextSiblingElement();
			String html = e.getInnerHTML();
			tp.add(new HTML(html), nl.getItem(i).getInnerText());
		}

		// Show the 'bar' tab initially.
		if (dictionary.get("selectTab") != null)
			tp.selectTab(new Integer(dictionary.get("selectTab")));
		else
			tp.selectTab(0);
		tp.setAnimationEnabled(new Boolean(dictionary.get("animationEnabled")));
		element.setInnerHTML("");
		initWidget(tp);

		tp.addBeforeSelectionHandler(new BeforeSelectionHandler<Integer>() {

			public void onBeforeSelection(BeforeSelectionEvent<Integer> event) {
				String zone = null;
				String url = "/examples/TabPanel:newStuff";
				if (zone != null)
					Tapestry.loadZone(zone, url);
			}
		});
	}
}
